import { getToken } from '/@/util/auth'
import { Base64 } from 'js-base64'
import website from '/@/config/website'

export const ajax = (data) => {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open(
      'POST',
      '/api/blade-measure/measure/userprojectgaugesubjectanswer/submit'
    )
    xhr.setRequestHeader('Content-Type', 'application/json')
    xhr.setRequestHeader(
      'Authorization',
      `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`
    )
    if (getToken()) {
      xhr.setRequestHeader('Blade-Auth', `bearer  ${getToken()}`)
    }
    xhr.send(JSON.stringify(data))

    xhr.onreadystatechange = () => {
      // 判断状态是否返回了所有结果
      if (xhr.readyState == 4) {
        //判断响应状态码 200-300之间
        if (xhr.status >= 200 && xhr.status < 300) {
          let res = { data: JSON.parse(xhr.response) }
          resolve(res)
        } else {
          reject(JSON.parse(xhr.response))
        }
      }
    }
  })
}
